namespace SimpleWebServices.Configuration
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;

    [XmlRoot("redirections")]
    public sealed class RedirectionCollection : Collection<RedirectionSetting>, IXmlSerializable
    {
        public RedirectionSetting this[string from]
        {
            get
            {
                return this
                    .Where(x => from.Equals(x.From, StringComparison.OrdinalIgnoreCase))
                    .FirstOrDefault();
            }
        }

        XmlSchema IXmlSerializable.GetSchema()
        {
            throw new NotSupportedException();
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (null == reader)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsEmptyElement)
            {
                reader.Read();
            }
            else
            {
                string name = reader.Name;
                while (true)
                {
                    if (XmlNodeType.EndElement == reader.NodeType && reader.Name == name)
                    {
                        reader.Read();
                        break;
                    }
                    else if ("redirect".Equals(reader.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        this.Add(reader.ReadOuterXml().Deserialize<RedirectionSetting>());
                    }
                    else
                    {
                        reader.Read();
                    }
                }
            }
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            if (null == writer)
            {
                throw new ArgumentNullException("writer");
            }

            foreach (RedirectionSetting setting in this)
            {
                writer.WriteRaw(setting.Serialize().CreateNavigator().OuterXml);
            }
        }
    }
}